package com.sinping.qh.service.auth.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sinping.qh.domain.auth.Resource;
import com.sinping.qh.domain.auth.RoleResource;
import com.sinping.qh.domain.auth.UserRole;
import com.sinping.qh.dto.auth.ResourceDTO;
import com.sinping.qh.repository.mysql.dao.ResourceMapper;
import com.sinping.qh.service.auth.IResourceService;
import com.sinping.qh.service.auth.IUserRoleService;
import com.sinping.qh.service.auth.IRoleResourceService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 杨云博
 * @since 2017-12-18
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @Autowired
    private IRoleResourceService roleResourceService;
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public List<Resource> getResourceByUserId(String userid) {
        if (userid == null || userid.trim().length() == 0) {
            return null;
        }
        List<UserRole> userRoles = userRoleService.getRolseByUserId(userid);
        // 用户的多个角色
        Set<String> roles = new HashSet<String>();
        for (UserRole userRole1 : userRoles) {
            if (StringUtils.isNotBlank(userRole1.getRoleId())) {
                roles.add(userRole1.getRoleId());
            }
        }
        if (roles.isEmpty()) {
            return null;
        }
        //根据角色 roles查询 资源id
        List<RoleResource> roleResources = roleResourceService.getRoleResourceByRoleIds(roles);
        if (roleResources == null) {
            return null;
        }
        Set<String> resoures = new HashSet<String>();
        for (RoleResource rR : roleResources) {
            if (rR.getResourceId() != null && !"".equals(rR.getResourceId().trim())) {
                resoures.add(rR.getResourceId());
            }
        }
        if (resoures.isEmpty()) {
            return null;
        }
         List<Resource> resources = this.getResourceByResourceIds(resoures);
         return resources;
    }

    @Override
    public List<Resource> getResourceByResourceIds(Set<String> ResourceIds) {
        if (CollectionUtils.isEmpty(ResourceIds)) {
            return null;
        }
       try {
           EntityWrapper<Resource> resourceEntityWrapper = new EntityWrapper<Resource>();
           resourceEntityWrapper.in("id", ResourceIds);
           List<Resource> resources = this.selectList(resourceEntityWrapper);
           return resources;
       }catch(Exception e){
            e.printStackTrace();
            return null;
       }
    }

    @Override
    public List<ResourceDTO> getResourceListTree(Resource resource) {
        EntityWrapper<Resource> ew = new EntityWrapper<>();
        if(resource==null){
            resource = new Resource();
        }
        //resource.setStatus(Const.STATUS_EFFECTIVE);
        ew.setEntity(resource);
        ew.orderBy("code");
        List<Resource> list = this.selectList(ew);

        List<ResourceDTO> resourceDTOList = this.createTreeByResource(list);

        return resourceDTOList;
    }

    @Override
    public List<ResourceDTO> createTreeByResource(List<Resource> resource) {
        List<ResourceDTO> resourceDTOList = new ArrayList<>();
        for (Resource re : resource) {
            if(re.getLev() == 1){
                ResourceDTO resDTO = new ResourceDTO(re);
                createTree(resDTO, resource);
                resourceDTOList.add(resDTO);
            }
        }
        return resourceDTOList;
    }


    /**
     * @方法名称: createTree
     * @功能描述: 递归创建菜单树
     * @作者:杨云博
     * @创建时间:2017/12/26 14:46
     * @param resourceDTO
    * @param resourceList
     * return void
     */
    private void createTree(ResourceDTO resourceDTO, List<Resource>  resourceList) {
        for (Resource res : resourceList) {
            if(res.getLev()!=null&&res.getLev() != 1&&resourceDTO.getId().equals(res.getParentId())){
                List<ResourceDTO> childrenList = resourceDTO.getChildren();
                if(childrenList == null) {
                    childrenList = new ArrayList<>();
                }
                ResourceDTO children = new ResourceDTO(res);
                childrenList.add(children);
                resourceDTO.setChildren(childrenList);
                createTree(children, resourceList);
            }
        }
    }

    @Override
    public boolean isExistUriAndRequestType(String uri, String reqType ,String id) {
        EntityWrapper<Resource> ew = new EntityWrapper<>();
        Resource whereResource = new Resource();
        whereResource.setUrl(uri);
        whereResource.setRequestType(reqType);
        ew.setEntity(whereResource);
        List<Resource> list = this.selectList(ew);
        if (list.size() > 0) {
            if(id != null && !id.equals("")){
                if(!list.get(0).getId().equals(id)){
                    return true;
                }else{
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}
